package com.guangzhou;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.client.RepChainJksClient;
import com.protos.Peer;
import com.websocket.wsCallBack;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 构造交易并post的封装类
 *
 * @author zyf
 */
public class RecordInvokePost {

    private static Logger logger = LoggerFactory.getLogger(RecordInvokePost.class);

    // 这里使用的是管理员节点1的私钥进行签名，也可以使用用户的私钥
    private final static RepChainJksClient client = new RepChainJksClient(
            "159.226.5.114:8081",
            "jks/121000005l35120456.node1.jks",
            "123",
            "121000005l35120456.node1");
    private final static Peer.CertId certId = Peer.CertId.newBuilder().setCreditCode("121000005l35120456").setCertName("node1").build();


    /**
     * 无回调的交易提交
     *
     * @param creditCode
     * @param evidenceData
     * @return
     * @throws Exception
     */
    public synchronized static String invokePost(String creditCode, String evidenceData) throws Exception {
        Peer.ChaincodeId recordTplCid = Peer.ChaincodeId.newBuilder().setChaincodeName("RecordProof").setVersion(1).build();
        String txid = UUID.randomUUID().toString().replace("-", "");
        // recordData，是要存证的数据
        String str_trans = JSON.toJSONString(new RecordProofData(creditCode + "_record", evidenceData));
        // txid也可以不指定，使用方法自己生成的，具体参考createTransactionForInvoke的用法
        Peer.Transaction proof = client.createTransactionForInvoke(txid, certId, recordTplCid, "recordProof", str_trans);
        JSONObject proofInvoke = client.postTranByString(JSON.toJSONString(Hex.encodeHexString(proof.toByteArray())));
        if (proofInvoke == null || proofInvoke.isEmpty()) {
            return null;
        } else {
            return txid;
        }
    }


    /**
     * 带有回调的交易提交
     *
     * @param recordCBT
     * @param creditCode   信用识别码，企业信用号
     * @param evidenceData 要存证的数据
     * @throws Exception
     */
    public synchronized static void invokePostByCallBack(RecordCallBackTest recordCBT, String creditCode, String evidenceData) throws Exception {
        Peer.ChaincodeId recordTplCid = Peer.ChaincodeId.newBuilder().setChaincodeName("RecordProof").setVersion(1).build();
        // evidenceData，是要存证的数据
        String str_trans = JSON.toJSONString(new RecordProofData(creditCode + "_record", evidenceData));
        // txid也可以不指定，使用方法自己生成的，具体参考createTransactionForInvoke的用法
        Peer.Transaction proof = client.createTransactionForInvoke(recordCBT.getTxid(), certId, recordTplCid, "recordProof", str_trans);
//        System.out.println(Thread.currentThread().getName() + "交易ID: " + proof.getId() + "  交易合约ID为： " + proof.getCid().getChaincodeName());
//        logger.info(Thread.currentThread().getName() + "交易ID: {}, 交易合约ID为： {}", proof.getId(), proof.getCid().getChaincodeName());
        // param2 与 param3 对应
        client.postTranByString(recordCBT, JSON.toJSONString(Hex.encodeHexString(proof.toByteArray())), proof);
    }

    /**
     * 通过 txid 检查交易是否已经上链
     *
     * @param txid 需要补录的交易的txid
     * @return
     */
    public synchronized static TranStatus getTranStatus(String txid) {
        if (txid == null || txid.isEmpty()) {
            throw new RuntimeException("txid 为空串或者null");
        }
        Peer.Transaction txr = client.getTransactionByTxid(txid);
        if (txr != null && txid.equals(txr.getId())) {
            return new TranStatus(txid, TranStatus.EXIST);
        } else {
            return new TranStatus(txid, TranStatus.NOTEXIST);
        }
    }


    /**
     * 获取本地时间
     *
     * @return
     */
    private static String getLocalTime() {
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        String time = localDateTime.format(formatter);
        return time;
    }

}
